<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>使用回调函数加载图片</title>
	</head>
	<body>
		<script>
			let loadImgs = 0

			function createImg(url) {
				let img = document.createElement('img')
				img.src = url
				document.body.append(img)

				img.onload = () => {
					console.log('Image loaded' + url)
					loadImgs++
				}

				img.onerror = () => {
					console.log('Image failed to load' + url)
					loadImgs++
				}
			}

			function loaded() {
				alert('Images loaded')
			}

			preloadImages(['1.jpg', '2.jpg', '3.jpg'], loaded)

			function preloadImages(urls, callback) {
				urls.forEach((url) => {
					createImg(url)
				})
				callback()
			}
		</script>
	</body>
</html>
